/*
 * Copyright © Jack魏 2022 - 2022, All Rights Reserved.
 */

package com.jack.thread.t02;

import org.junit.Test;

/**
 * 线程停止演示
 *
 * @author Jack魏
 * @since 2022/11/15 23:58
 */
public class JavaThreadStopDemo {

    /**
     * 1.测试使用stop方式
     */
    static class StopThread1 extends Thread {
        @Override
        public void run() {
            // 这里的任务一直打印信息
            while (true) {
                System.out.println(Thread.currentThread().getName() + "===我是继承Thread类实现方式");
            }
        }
    }

    /**
     * 2.测试使用interrupt方式
     */
    static class StopThread2 extends Thread {
        @Override
        public void run() {
            // 输出中断标识位
            System.out.println(Thread.currentThread().getName() + " start interrupt flag === " + this.isInterrupted());
            // 判断是否有中断请求
            while (!this.isInterrupted()) {
                // 输出中断标识位
                System.out.println(Thread.currentThread().getName() + " while interrupt flag === " + this.isInterrupted());
            }
            // 输出中断标识位：Thread-0 end interrupt flag === true
            System.out.println(Thread.currentThread().getName() + " end interrupt flag === " + this.isInterrupted());
        }
    }

    /**
     * 3.测试使用静态interrupt方式
     */
    static class StopThread3 extends Thread {
        @Override
        public void run() {
            // 输出中断标识位
            System.out.println(Thread.currentThread().getName() + " start interrupt flag === " + this.isInterrupted());
            // 判断是否有中断请求，静态方法：结束之后将中断标识位清理（false）
            while (!Thread.interrupted()) {
                // 输出中断标识位
                System.out.println(Thread.currentThread().getName() + " while interrupt flag === " + this.isInterrupted());
            }
            // 输出中断标识位：Thread-0 end interrupt flag === false
            System.out.println(Thread.currentThread().getName() + " end interrupt flag === " + this.isInterrupted());
        }
    }

    /**
     * 1.测试 stop
     *
     * @throws InterruptedException
     */
    @Test
    public void testStop1() throws InterruptedException {
        StopThread1 stop1 = new StopThread1();
        stop1.start();
        // 延迟指定毫秒，可调节
        Thread.sleep(3);
        stop1.stop();
    }

    /**
     * 2.测试interrupt
     *
     * @throws InterruptedException
     */
    @Test
    public void testStop2() throws InterruptedException {
        StopThread2 stop2 = new StopThread2();
        stop2.start();
        // 延迟指定毫秒，可调节
        Thread.sleep(8);
        stop2.interrupt();
    }

    /**
     * 3.测试静态interrupt
     *
     * @throws InterruptedException
     */
    @Test
    public void testStop3() throws InterruptedException {
        StopThread3 stop3 = new StopThread3();
        stop3.start();
        // 延迟指定毫秒，可调节
        Thread.sleep(8);
        stop3.interrupt();
    }
}
